package com.heepay;

import com.alibaba.fastjson.JSON;
import com.heepay.api.DefaultHeepayClient;
import com.heepay.api.HeepayClient;
import com.heepay.common.CertRequest;
import com.heepay.common.MyKey;
import com.heepay.request.BaseRequest;
import com.heepay.request.SignRequest;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 该接口为快捷签约接口
 */
public class PageSign {

    /**
     * 主方法，程序入口
     * 负责创建签名请求和证书请求以及处理请求的发送和响应
     */
    public static void main(String[] args) {
        // 业务参数
        SignRequest signRequest = createSignRequest();
        System.out.println("待加密------------------------------------------------------------------------>" + JSON.toJSONString(signRequest));

        // 公共请求参数
        CertRequest certRequest = createCertRequest();
        BaseRequest baseRequest = new BaseRequest();
        baseRequest.setBiz_content(JSON.toJSONString(signRequest));

        try {
            HeepayClient client = new DefaultHeepayClient(certRequest);
            client.submitSign(baseRequest);
        } catch (Exception e) {
            handleException(e);
        }
    }

    /**
     * 创建签名请求对象
     * 初始化签名请求的必要参数
     * @return SignRequest 签名请求对象
     */
    private static SignRequest createSignRequest() {
        SignRequest signRequest = new SignRequest();
        long tenDigitTimestamp = System.currentTimeMillis() / 1000;
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        signRequest.setOut_trade_no(String.valueOf(tenDigitTimestamp));
        signRequest.setOut_trade_time(sd.format(new Date()));
        signRequest.setMerch_user_id("123456");
        //signRequest.setNotify_url("https://www.baidu.com/");
        //signRequest.setReturn_url("https://www.baidu.com/");

        signRequest.setBank_card_no("");
        signRequest.setBank_user_name("");
        signRequest.setMobile("");
        signRequest.setCert_no("");

        // 如果为集团户模式，需要设置子商户号
        // signRequest.setSub_merch_id("");

        return signRequest;
    }

    /**
     * 创建证书请求对象
     * 初始化证书请求的必要参数
     * @return CertRequest 证书请求对象
     */
    private static CertRequest createCertRequest() {
        CertRequest certRequest = new CertRequest();
        certRequest.setServerUrl("https://pay.Heepay.com/API/PageSign/Index.aspx");
        certRequest.setMerchantId("1664502");
        certRequest.setVersion("1.0");
        certRequest.setMethod("heepay.agreement.bank.sign.page");
        certRequest.setPrivateKeyStr(MyKey.privateKeystr);
        certRequest.setPublicKeyStr(MyKey.publicKeystr);

        return certRequest;
    }

    /**
     * 处理异常
     * @param e 异常对象
     */
    private static void handleException(Exception e) {
        System.err.println("请求失败，错误信息：" + e.getMessage());
        e.printStackTrace();
    }
}
